//基本语法
import React, { Component,Fragment} from 'react';
import Item from "./item";
//此处可以省略index.js  ../store/index.js == ../store
import store from "../store";
import { getInputChangeAction, getAddItmeAction, getDelItemAction } from "../store/actionCreators";

export default class App extends Component {

    constructor(props) {
      super(props);
      this.state = store.getState();
      store.subscribe(this.handlerStoreChange);
    }


    //当组件的state或者props被改变时 render()函数都会被重新执行
	render() {
      return (
        <Fragment>
            <div>
                {/*label for替换成htmlFor 等于需要聚焦的input标签的ID*/}
                {/*不推荐ref 容易出错  ref={(input) => {this.input=input}}*/}
                <label htmlFor="insertArea">请输入内容</label>
            	<input  id="insertArea" value={this.state.inputValue} onChange={this.handlerInputChange}/>
            	<button onClick={this.handlerButClick}>提交</button>
            </div>
            {/*不推荐ref 容易出错此处有坑 因为this.setState是异步调用*/}
        	<ul ref={(ul) => {this.ul = ul}}>
                {this.getTodoItem()}
        	</ul>
        </Fragment>
      );
    }
    //可执行函数
    getTodoItem(){
        /*当标签中加入dangerouslySetInnerHTML={{__html:item}}时文本内有标签时自动渲染 li中就不要写<item>*/
        /*<li key={index} onClick={this.handlerItemDelete.bind(this,index)} dangerouslySetInnerHTML={{__html:item}}></li>*/
        /*父组件向子组件传递参数用属性的方法传递，传递方法需要强制绑定父组件的this否则会出现找不到方法*/
        return this.state.list.map((item,index) => {
                    return <Item key = {index} context = {item} index = {index} handlerItemDelete = {this.handlerItemDelete}/>
        })
    }
    //事件绑定 希望this.setState用函数修改 如果传数组用[...加新数组赋值] 打撒后创建新数组
    handlerInputChange = (event) => {
        // 改变自己state
        // const value = this.input.value;
        // this.setState(()=>({
        //     inputValue:value
        // }))
        const action = getInputChangeAction(event.target.value);
        store.dispatch(action);
    }

    handlerButClick = () => {
        //prevState 等价于 this.state
        // this.setState((prevState) => ({
        //     inputValue:'',
        //     list:[...prevState.list,prevState.inputValue]
        // }),() => {
        //     //异步回调
        //     console.log(this.ul.querySelectorAll('div').length);
        // })
        const action = getAddItmeAction();
        store.dispatch(action);
    }

    handlerItemDelete = (index) => {
        //第一种
        // const list = [...this.state.list];
        // list.splice(index,1);
        // this.setState({
        //     list:list
        // })
        //第二种
        // this.setState((prevState)=>{
        //     const list = [...prevState.list];
        //     list.splice(index,1);
        //     return {list}
        // })
        //第三种
        const action = getDelItemAction(index);
        store.dispatch(action);
    }

    handlerStoreChange = () =>{
        this.setState(store.getState())
    }
}
